package com.laikan.reader.bookfriend.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.GlobalAlertDialogTool;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.AndroidUtils;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.UpdateUtil;
import com.laikan.reader.article.activity.BookFocusActivity;
import com.laikan.reader.bookfriend.bean.PersonalInfoBean;
import com.laikan.reader.bookfriend.mactivity.AutherActivity;
import com.laikan.reader.bookstart.activity.HomeActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.*;
import com.laikan.reader.core.utils.*;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.jsoup.nodes.Document;

import java.io.*;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.laikan.reader.core.events.LaiKanEvent.EVENT_ID_UPDATE_VERSION;

/**
 * 个人中心页面
 */
public class PersonalActivity extends BasicActivity implements OnClickListener {

    public static final File FILE_SDCARD = Environment.getExternalStorageDirectory();
    public static final File FILE_LOCAL = new File(FILE_SDCARD, "vCar");
    public static final File FILE_PIC_SCREENSHOT = new File(FILE_LOCAL, "images/screenshots");
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 1000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
    private final static int SCANNIN_GREQUEST_CODE = 8;
    VersionDetialInfo detailInfo;
    Animation animation, animation1;
    String PERSONFILEPATH = "/LaikanReader/person/json";
    private com.facebook.drawee.view.SimpleDraweeView icon, personal_image;
    private PersonalBean<TickBean> mData;
    private TextView name, levon;
    private Intent dataIntent = null;
    private String file_url;
    private int money = 0;
    private RelativeLayout layout_item2, layout_item3, layout_item4, layout_item5, layout_item4_1, layout_item4_3, layout_item6, layout_item7, layout_item9, layout_account,
        layout_sign_in,collect_layout,home_layout;
    /**
     * 用户未登录布局与已登录布局
     */
    private RelativeLayout unlogin_layout, login_layout, top_layout;
    /**
     * 我的消息布局
     */
    private RelativeLayout layout_message, personal_title;
    /**
     * 用户名，会员等级，个性签名
     */
    private TextView unlogin_bookname, login_bookname, login_vip_tv;
    /**
     * 显示用户来看币、阅读券、签到天数，分别点击后跳转相应的二级页面。标题文本
     */
    private TextView lk_money, lk_rdquan, text_title;
    private ScrollView scrollview;
    private ImageView chongzhi_img, message_img, xiangdu_img, xitong_setting_img, checkversion_img, feedback_img, about_lk_img, iv_signin_arrow;
    private ImageView chongzhi_right, message_right, xiangdu_right, xitong_right, check_right, feedback_right, aboutlk_right, login_personal_right, unlogin_personal_right,
    account_right,collect_right,home_right;
    private Bitmap chongzhi_bmp, message_bmp, xiangdu_bmp, xitong_setting_bmp, checkversion_bmp, feedback_bmp, about_lk_bmp, layout_right_bmp, two_dimenson_codes_bmp;
    Drawable drawable_chongzhi_img, drawable_message_img, drawable_xiangdu_img, drawable_xitong_setting_img, drawable_checkversion_img, drawable_feedback_img, drawable_about_lk_img, drawable_layout_right_img, drawable_layout_right_img_white;
    private View top_line;
    private File file = null;
    private ImageView two_dimenson_codes, per_mess;
    private Bitmap per_mess_bmp, per_mess_bitmap;
    private long mkeyTime;
    private TextView version;
    private TextView laikanbi, laikannotes;
    private ArrayList<Integer> payratio = new ArrayList<Integer>();
    private boolean payAction = false;
    private LinearLayout top_mess;
    private Document doc;
    private TelephonyManager tm;
    private LinearLayout top_bottom;
    private ImageView person_mess4_3;
    private TextView type_name4_3, laikannotes4_3;
    private String activityName, activityUrl;
    private ImageView person_mess4_1, xiangdu_red_point;
    Drawable drawable_per_mess, drawable_two_code;
    private ImageView feedback_red_point; //意见反馈图标对应的小红点
    private LoadingDialog mloadingDialog;
    private boolean feedback_update;
    private ImageView per_mess_new, message_red_point, check_red_point;

    public static boolean isNumeric1(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_personal_new);
        openEventBus();

        animation = AnimationUtils.loadAnimation(mContext, R.anim.bottom_to_top);
        animation1 = AnimationUtils.loadAnimation(mContext, R.anim.top_to_bottom);
        SPUtil.putBoolean("login_laikan_setting", false);
        tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        System.out.println(SPUtil.getString("user_id", ""));
        LaikanApplication.windowManager = getWindowManager();
        //初始化布局
        unlogin_layout = (RelativeLayout)findViewById(R.id.id_unlogin_layout);
        login_layout = (RelativeLayout)findViewById(R.id.id_login_layout);
        top_layout = (RelativeLayout)findViewById(R.id.top_layout);
        //初始化TextView
        unlogin_bookname = (TextView)findViewById(R.id.id_unlogin_bookname);
        login_bookname = (TextView)findViewById(R.id.id_login_bookname);
        login_vip_tv = (TextView)findViewById(R.id.id_login_vip_tv);
        lk_money = (TextView)findViewById(R.id.lk_money);
        lk_rdquan = (TextView)findViewById(R.id.lk_rdquan);
        //初始化ImageView
        personal_image = (com.facebook.drawee.view.SimpleDraweeView)findViewById(R.id.personal_image);
        scrollview = (ScrollView)findViewById(R.id.scrollview);
        version = (TextView)findViewById(R.id.version); //版本

        layout_item2 = (RelativeLayout)findViewById(R.id.layout_item2);//充值
        layout_item4_1 = (RelativeLayout)findViewById(R.id.layout_item4_1);//我的享读
        layout_item5 = (RelativeLayout)findViewById(R.id.layout_item5);// 检查版本
        layout_item6 = (RelativeLayout)findViewById(R.id.layout_item6);//意见反馈
        layout_item7 = (RelativeLayout)findViewById(R.id.layout_item7);//系统设置
        layout_account = (RelativeLayout)findViewById(R.id.layout_account);//我的账户
        collect_layout = (RelativeLayout)findViewById(R.id.collect_layout); //我的收藏
        home_layout = (RelativeLayout)findViewById(R.id.home_layout);//我的主页
        version.setText("V " + AndroidUtils.getCurrentAppVer(mContext));
        xiangdu_red_point = (ImageView)findViewById(R.id.xiangdu_red_point);// 我的享读 - 红点图标
        per_mess_new = (ImageView)findViewById(R.id.per_mess_new); //头部的信息图标

        chongzhi_img = (ImageView)findViewById(R.id.chongzhi_img);
        message_img = (ImageView)findViewById(R.id.message_img);
        xiangdu_img = (ImageView)findViewById(R.id.xiangdu_img);
        xitong_setting_img = (ImageView)findViewById(R.id.xitong_setting_img);
        checkversion_img = (ImageView)findViewById(R.id.checkversion_img);
        feedback_img = (ImageView)findViewById(R.id.feedback_img);
        about_lk_img = (ImageView)findViewById(R.id.about_lk_img);
        chongzhi_right = (ImageView)findViewById(R.id.chongzhi_right);
        message_right = (ImageView)findViewById(R.id.message_right);
        xiangdu_right = (ImageView)findViewById(R.id.xiangdu_right);
        xitong_right = (ImageView)findViewById(R.id.xitong_right);
        check_right = (ImageView)findViewById(R.id.check_right);
        feedback_right = (ImageView)findViewById(R.id.feedback_right);
        aboutlk_right = (ImageView)findViewById(R.id.aboutlk_right);
        account_right = (ImageView)findViewById(R.id.account_right);
        iv_signin_arrow = (ImageView)findViewById(R.id.iv_signin_arrow);
        login_personal_right = (ImageView)findViewById(R.id.login_personal_right);
        unlogin_personal_right = (ImageView)findViewById(R.id.unlogin_personal_right);
        collect_right = (ImageView)findViewById(R.id.collect_right);
        home_right = (ImageView)findViewById(R.id.home_right);
        top_bottom = (LinearLayout)findViewById(R.id.top_bottom);
        feedback_red_point = (ImageView)findViewById(R.id.feedback_red_point);
        message_red_point = (ImageView)findViewById(R.id.message_red_point);
        check_red_point = (ImageView)findViewById(R.id.check_red_point);

        text_title = (TextView)findViewById(R.id.text1);
        text_title.setVisibility(View.GONE);
        layout_message = (RelativeLayout)findViewById(R.id.layout_message);
        personal_title = (RelativeLayout)findViewById(R.id.personal_title);
        top_line = findViewById(R.id.top_divider);
        laikannotes = (TextView)findViewById(R.id.laikannotes4); //阅读券，目前此功能暂不实现
        laikanbi = (TextView)findViewById(R.id.laikanbi);   //K币，目前此功能暂不实现
        layout_item3 = (RelativeLayout)findViewById(R.id.layout_item3); //K币布局,暂不实现
        layout_item4 = (RelativeLayout)findViewById(R.id.layout_item4); //阅读券布局,暂不实现
        person_mess4_3 = (ImageView)findViewById(R.id.person_mess4_3); //双蛋狂欢
        type_name4_3 = (TextView)findViewById(R.id.type_name4_3);
        laikannotes4_3 = (TextView)findViewById(R.id.laikannotes4_3);
        layout_item4_3 = (RelativeLayout)findViewById(R.id.layout_item4_3); //双蛋狂欢布局，暂不实现
        layout_sign_in = (RelativeLayout)findViewById(R.id.layout_sign_in);//我的签到
        two_dimenson_codes = (ImageView)findViewById(R.id.two_dimenson_codes);//二维码扫描图标
        layout_item9 = (RelativeLayout)findViewById(R.id.layout_item9);
        top_mess = (LinearLayout)findViewById(R.id.top_mess); //充值 - 首充有礼布局
        per_mess = (ImageView)findViewById(R.id.per_mess); //标题右侧信封图标

        //初始化代码设置图片颜色
        initBmp();

    }

    /**
     * 初始化代码设置图片颜色
     */
    public void initBmp() {
        chongzhi_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_chongzhi_small);
        message_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_message_small);
        xiangdu_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_xiangdu_small);
        xitong_setting_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_xitong_setting);
        checkversion_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_checkversion_small);
        feedback_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_feedback_small);
        about_lk_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_aboutlk_small);
        layout_right_bmp = PublicUtil.readBitMap(mContext, R.drawable.lk_enter_small);
        drawable_chongzhi_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(chongzhi_bmp, Color.parseColor("#66ccdd")));
        drawable_message_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(message_bmp, Color.parseColor("#66ccdd")));
        drawable_xiangdu_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(xiangdu_bmp, Color.parseColor("#66ccdd")));
        drawable_xitong_setting_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(xitong_setting_bmp, Color.parseColor("#66ccdd")));
        drawable_checkversion_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(checkversion_bmp, Color.parseColor("#66ccdd")));
        drawable_feedback_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(feedback_bmp, Color.parseColor("#66ccdd")));
        drawable_about_lk_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(about_lk_bmp, Color.parseColor("#66ccdd")));
        drawable_layout_right_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(layout_right_bmp, Color.parseColor("#cccccc")));
        drawable_layout_right_img_white = new BitmapDrawable(PublicUtil.getAlphaBitmap(layout_right_bmp, Color.parseColor("#ffffff")));

        chongzhi_img.setImageDrawable(drawable_chongzhi_img);
        message_img.setImageDrawable(drawable_message_img);
        xiangdu_img.setImageDrawable(drawable_xiangdu_img);
        xitong_setting_img.setImageDrawable(drawable_xitong_setting_img);
        checkversion_img.setImageDrawable(drawable_checkversion_img);
        feedback_img.setImageDrawable(drawable_feedback_img);
        about_lk_img.setImageDrawable(drawable_about_lk_img);

        chongzhi_right.setImageDrawable(drawable_layout_right_img);
        message_right.setImageDrawable(drawable_layout_right_img);
        xiangdu_right.setImageDrawable(drawable_layout_right_img);
        xitong_right.setImageDrawable(drawable_layout_right_img);
        check_right.setImageDrawable(drawable_layout_right_img);
        feedback_right.setImageDrawable(drawable_layout_right_img);
        aboutlk_right.setImageDrawable(drawable_layout_right_img);
        account_right.setImageDrawable(drawable_layout_right_img);
        collect_right.setImageDrawable(drawable_layout_right_img);
        home_right.setImageDrawable(drawable_layout_right_img);
        iv_signin_arrow.setImageDrawable(drawable_layout_right_img);
        login_personal_right.setImageDrawable(drawable_layout_right_img_white);
        unlogin_personal_right.setImageDrawable(drawable_layout_right_img_white);
        per_mess_bitmap = PublicUtil.readBitMap(mContext, R.drawable.person_mess_new);
        drawable_per_mess = new BitmapDrawable(PublicUtil.getAlphaBitmap(per_mess_bitmap, Color.parseColor("#66ccdd")));
        two_dimenson_codes_bmp = PublicUtil.readBitMap(mContext, R.drawable.two_dimenson_code);
        drawable_two_code = new BitmapDrawable(PublicUtil.getAlphaBitmap(two_dimenson_codes_bmp, Color.parseColor("#66ccdd")));
    }

    /**
     * 设置数据
     */
    private void setView() {
        login_layout.setVisibility(View.VISIBLE);
        unlogin_layout.setVisibility(View.GONE);

        //        if (mData.isHaveShareRead()) { //判断是否有未领取享读礼包
        //            xiangdu_red_point.setVisibility(View.VISIBLE);
        //        } else {
        //            xiangdu_red_point.setVisibility(View.GONE);
        //        }
        laikanbi.setText((int)(Double.parseDouble(mData.getUserBalance()) * 100) + "");
        laikannotes.setText(mData.getData().get(0).getNumber());

        //登录后的用户名
        login_bookname.setText(mData.getUserName());
        money = (int)(Double.parseDouble(mData.getUserBalance()) * 100);
        lk_money.setText(money + " K币");
        lk_rdquan.setText(mData.getData().get(0).getNumber() + " 阅读券");

        //设置用户会员
        if (mData.getMemberLevel().equals("-1")) {
            login_vip_tv.setText("");
        }else {
            login_vip_tv.setText("LV" + mData.getMemberLevel());
        }
        //设置用户头像
        personal_image.setImageURI(Uri.parse(mData.getUserIcon()));
        feedback_update = mData.isHaveNewMessage();
        if (feedback_update) {
            feedback_red_point.setVisibility(View.VISIBLE);
            SPUtil.putBoolean("feedback_red_point",true);
        }else {
            feedback_red_point.setVisibility(View.GONE);
            SPUtil.putBoolean("feedback_red_point",false);
        }

        SystemUtil.checkRedDotShow();

        payAction = mData.isPayAction(); //判断用户是否充过值
        if (payAction) { //否
            //            top_mess.setVisibility(View.VISIBLE);
        }else {
            top_mess.setVisibility(View.GONE);
        }
        payratio = mData.getPayratio(); //首充奖励额度

    }

    @Override
    protected void parseEvent(BasicEvent event) {
        super.parseEvent(event);
        switch (event.getEventID()){
            case EVENT_ID_UPDATE_VERSION:
                if(SPUtil.getBoolean("checkversion_update",false)){
                    check_red_point.setVisibility(View.VISIBLE);
                }else{
                    check_red_point.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SPUtil.getBoolean("message_list", false)) {
            Intent intent = new Intent();
            intent.putExtra("mHtmlUrl", SPUtil.getString("refresh_mess_url", ""));
            intent.putExtra("title", SPUtil.getString("refresh_mess_title", ""));
            SPUtil.putBoolean("message_" + SPUtil.getString("refresh_mess_id", ""), true);
            intent.setClass(mContext, MessageActivity.class);
            startActivity(intent);
        }
        if (ActivityUitl.isNetworkAvailable(mContext)) {
            if (BookFileUtils.isNoLogin()) {
                no_login();
                personal_image.setImageResource(R.drawable.lk_default_personal_image_blue);
            }else {
                readFile();
                getData();
            }
        }else {
            if (BookFileUtils.isNoLogin()) {
                no_login();
                personal_image.setImageResource(R.drawable.lk_default_personal_image_blue);
            }else {
                //                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                readFile();
            }
        }
        if (SPUtil.getBoolean("update_message", false) && !BookFileUtils.isNoLogin()) {
            message_red_point.setVisibility(View.VISIBLE);
        }else {
            message_red_point.setVisibility(View.GONE);
        }
        SPUtil.putBoolean("login_laikan_setting", false);
        if (SPUtil.getBoolean("isOpenFestivalArray", false)) {
            SPUtil.putBoolean("isOpenFestivalArray", false);
            // getGitfBooks();
            // 弹出领取阅读券提示框
            Intent intent = new Intent(mContext, FestivalCouponActivity.class);
            startActivity(intent);
        }
        if (SPUtil.getBoolean("refresh_tab", false)) {
            HomeActivity.setCheckById(R.id.radio_bookstore, 1);
        }
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        mloadingDialog = new LoadingDialog(mContext);
        SPUtil.putBoolean("signedAction", false);
        if (SPUtil.getBoolean("share_red_point", true)) {
            xiangdu_red_point.setVisibility(View.VISIBLE);
        }else {
            xiangdu_red_point.setVisibility(View.GONE);
        }
        if (SPUtil.getBoolean("checkversion_update", false)) {
            check_red_point.setVisibility(View.VISIBLE);
        }else {
            check_red_point.setVisibility(View.GONE);
        }
    }



    /**
     * 未登录界面显示状态
     */
    public void no_login() {
        SPUtil.putString("user_id", "0");
        SPUtil.putString("token", "");
        SPUtil.putBoolean("login_laikan_setting", false);
        //        top_mess.setVisibility(View.VISIBLE);
        //        haveShareRead.setVisibility(View.VISIBLE);
        login_layout.setVisibility(View.GONE);
        unlogin_layout.setVisibility(View.VISIBLE);
        personal_image.setImageResource(R.drawable.lk_default_personal_image_blue);
        unlogin_bookname.setText(R.string.personal_please_login);
        login_vip_tv.setText("");

    }

    /**
     * 访问网络，获取个人中心数据
     */
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("channel", "1");
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<PersonalBean<TickBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<PersonalBean<TickBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
                if (result != null) {
                    if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                        if (result.getError_no().equals("201")) {
                            AccountManager.getInstance().clearAccountData();
                            no_login();
                        }
                        ToastMgr.showShortToast(result.getError_msg());
                    }else {
                        mData = result.getData();
                        setView();

                        if (result.getData().getUsercenterMenu() == null) {
                            layout_item4_3.setVisibility(View.GONE);
                        }else {
                            setActivity(result.getData().getUsercenterMenu());
                        }
                        saveFile(httpResponse.responseContent, PERSONFILEPATH);
                    }
                }else {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。34");
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_user_deatil);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
    }

    private void setActivity(ActivityBean activityBean) {
        layout_item4_3.setVisibility(View.VISIBLE);
        activityName = activityBean.getName();
        activityUrl = activityBean.getUrl();
        person_mess4_3.setImageURI(Uri.parse(activityUrl));

        type_name4_3.setText(activityBean.getName());
        laikannotes4_3.setText(activityBean.getIntroduce());
    }

    private void uploadimg(File file, int width, int height) {
        HashMap map = new HashMap();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("left", "0");
        map.put("top", "0");
        map.put("width", width + "");
        map.put("height", height + "");

        if (!file.exists()) {
            Toast.makeText(getApplicationContext(), "图片不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "iconupload");
        requester.setMapBody(map);
        requester.setPartFileName("uploadfile");
        requester.setPartFile(file);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    @Override
    protected void setListener() {
        //        two_dimenson_codes.setOnClickListener(this);
        layout_item2.setOnClickListener(this);
        layout_item3.setOnClickListener(this);
        layout_item4.setOnClickListener(this);
        layout_sign_in.setOnClickListener(this);
        layout_item4_1.setOnClickListener(this);
        layout_item4_3.setOnClickListener(this);
        layout_item5.setOnClickListener(this);
        layout_item6.setOnClickListener(this);
        layout_item7.setOnClickListener(this);
        layout_account.setOnClickListener(this);
        version.setOnClickListener(this);
        per_mess_new.setOnClickListener(this);
        top_layout.setOnClickListener(this);
        collect_layout.setOnClickListener(this);
        home_layout.setOnClickListener(this);
    }

    private void goToAccount() {
        if (BookFileUtils.isNoLogin()) {
            startActivity(new Intent(mContext, LoginActivity.class));
        }else {
            if (mData != null&&mData.getData()!=null) {
                try {
                    Intent intent = new Intent(PersonalActivity.this, Account.class);
                    intent.putExtra("money", money);// K币
                    intent.putExtra("notes", mData.getData().get(0).getNumber());
                    intent.putExtra("VIP", mData.getMemberLevel());// 会员等级
                    intent.putExtra("grow", mData.getMemberScore());
                    intent.putExtra("recommend", mData.getData().get(1).getTotal());
                    if (mData.getData().size() >= 3) {
                        intent.putExtra("gold", mData.getData().get(2).getTotal());
                    }
                    intent.putExtra("payAction", payAction);
                    intent.putIntegerArrayListExtra("payratio", payratio);
                    startActivity(intent);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                KLog.e("mData is null.");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_layout:
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent(this,AutherActivity.class);
                    intent.putExtra("userId",SPUtil.getString("user_id",""));
//                    intent.putExtra("type","me");//标记intent的来源为我的页面
                    startActivity(intent);
                }
                break;
            case R.id.collect_layout:
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    startActivity(new Intent(mContext, MyCollect.class));
                }
                break;
            case R.id.top_bottom:
                break;
            case R.id.layout_account:
                MobclickAgent.onEvent(mContext, "my_Account");
                goToAccount();
                break;
            case R.id.top_layout: //头部布局跳转我的资料页
                MobclickAgent.onEvent(mContext, "my_information");
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    Intent intentMaterial = new Intent(mContext, PersonalInfoActivity.class);
                    PersonalInfoBean pib = new PersonalInfoBean();
                    pib.setUserId(SPUtil.getString("user_id", ""));
                    if (mData != null) {
                        pib.setUserAvatorUrl(mData.getUserIcon());
                        pib.setUserName(mData.getUserName());
                        pib.setUserAccountChannel(mData.getUsertype());
                        pib.setUserGender(mData.getGender()+"");
                        pib.setUserBirthday(mData.getBirthday());
                        if(mData.getIntro()!= null){
                            pib.setUserIntroduce(mData.getIntro());
                        }
                    }
                    intentMaterial.putExtra("personalInfoBean", pib);
                    startActivity(intentMaterial);
                }
                break;
            case R.id.two_dimenson_codes:
                Intent intents = new Intent();
                intents.setClass(mContext, MipcaActivityCapture.class);
                intents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intents, SCANNIN_GREQUEST_CODE);
                break;
            case R.id.layout_sign_in: // 签到文本
                if (SystemUtil.isLogin()) {
                    Intent intentSign = new Intent(mContext, SignInActivity.class);
                    mContext.startActivity(intentSign);
                }else {
                    startActivity(new Intent().setClass(mContext, LoginActivity.class));
                }
                break;
            case R.id.per_mess_new: //头部消息图标
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    message_red_point.setVisibility(View.GONE);
                    SPUtil.putBoolean("update_message", false);
                    startActivity(new Intent().setClass(mContext, MessageActivity.class));
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }
                break;
            case R.id.layout_item7: //系统设置
                MobclickAgent.onEvent(mContext, "my_systemSetting");
                startActivity(new Intent().setClass(mContext, SettingActivity.class));
                break;
            case R.id.layout_item9: //关于来看
                Intent intent9 = new Intent();
                intent9.putExtra("mHtmlUrl", APIProtocol.getRootURL() + "gy102");
                intent9.putExtra("title", "关于");
                intent9.setClass(mContext, WebViewActivity_Mess.class);
                startActivity(intent9);
                break;
            case R.id.lk_money: //K币文本
                goToAccount();
                break;

            case R.id.layout_item2: //充值

                MobclickAgent.onEvent(mContext, "my_Recharge");
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, BookFocusActivity.class);
                    startActivity(intent);
                }else {
                    startActivity(new Intent().putIntegerArrayListExtra("payratio", payratio).putExtra("payAction", payAction).setClass(mContext, BookFocusActivity.class));
                }
                break;
            case R.id.layout_item3: //磨铁币
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    Intent intent1 = new Intent(PersonalActivity.this, Account.class);
                    intent1.putExtra("money", money);
                    startActivity(intent1);
                }
                break;
            case R.id.layout_item4_1: // 享读
                MobclickAgent.onEvent(mContext, "my_myShare");
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    xiangdu_red_point.setVisibility(View.GONE);
                    SPUtil.putBoolean("share_red_point", false);
                    SystemUtil.checkRedDotShow();
                    Intent intent2 = new Intent(mContext, MyShareRead.class);
                    startActivity(intent2);
                }
                break;
            case R.id.layout_item4_3: //双蛋狂欢
                if (SystemUtil.isLogin()) {
                    Intent eggActivity = new Intent();
                    eggActivity.putExtra("mHtmlUrl", activityUrl);
                    eggActivity.putExtra("title", activityName);
                    eggActivity.setClass(mContext, EventWebViewActivity.class);
                    startActivity(eggActivity);
                }else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.layout_item5: //检测更新
                MobclickAgent.onEvent(mContext, "my_cheakUp");
                if (ActivityUitl.isNetworkAvailable(mContext)) {
                    UpdateUtil.checkVersion(mContext, true);
                }else {
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
                break;
            case R.id.layout_item6: //意见反馈
                MobclickAgent.onEvent(mContext, "my_ideabackfeed");

                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    startActivity(new Intent().setClass(mContext, FeedBackActivity.class).putExtra("version", AndroidUtils.getCurrentAppVer(mContext)));
                }
                break;
            case R.id.version:
//                openTestDialog();
                break;
            default:
                break;
        }
    }

    private void openTestDialog(){
        if (DeviceUtil.getMetaDataStringValue(this, "UMENG_CHANNEL").equals("test")){

            GlobalAlertDialogTool.getInstance().showHiddenDebugDialog(PersonalActivity.this);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data != null) {
            if (requestCode == 5) {
                String nickName = data.getStringExtra("nick");
                name.setText(nickName);
            }
        }
        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {

                // 如果是直接从相册获取
                case SCANNIN_GREQUEST_CODE:
                    if (resultCode == RESULT_OK) {
                        try {

                            Bundle bundle = data.getExtras();
                            // 显示扫描到的内容
                            String reg = bundle.getString("result");

                            if (!isNumeric1(bundle.getString("result"))) {
                                String regEx = "/r/(.*?)/";
                                Pattern p = Pattern.compile(regEx);
                                Matcher m = p.matcher(bundle.getString("result"));
                                if (m.find()) {
                                    String sequence = m.group(1);
                                    SPUtil.putString("sequence", sequence);
                                    KLog.e("823 sequence = " + sequence);
                                }else {
                                    if (reg.startsWith("http://")) {
                                        Intent intent = new Intent(mContext, MSCodeScanner.class);
                                        intent.putExtra("mHtmlUrl", bundle.getString("result"));
                                        intent.putExtra("title", "二维码扫描");
                                        startActivity(intent);
                                    }else {
                                        ToastMgr.showShortToast("内部扫码，暂只支持来看官方活动");
                                    }
                                }
                            }else {
                                ToastMgr.showShortToast("内部扫码，暂只支持来看官方活动");
                            }

                            //
                        }catch (Exception e) {
                            // TODO: handle exception

                        }

                    }
                    break;
                case 1:
                    if (data != null) {
                        startPhotoZoom(data.getData());
                        //                    file = new File(getRealFilePath(mContext, data.getData()));
                        file = new File(getPath(data.getData()));
                    }
                    break;
                // 如果是调用相机拍照时
                case 2:
                    File temp = new File(Environment.getExternalStorageDirectory() + "/LaikanReader/person.jpg");
                    file = temp;
                    startPhotoZoom(Uri.fromFile(temp));

                    break;
                // 取得裁剪后的图片
                case 3:
                    /**
                     * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                     * 当前功能时，会报NullException，小马只 在这个地方加下，大家可以根据不同情况在合适的 地方做判断处理类似情况
                     *
                     */
                    if (data != null) {
                        dataIntent = data;
                        setPicToView(data);

                    }
                    break;
                default:
                    break;

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 弹出是否从相册中选择还是拍照获取图片
     */
    private void ShowPickDialog() {
        new AlertDialog.Builder(mContext).setTitle(R.string.personal_info_setup).setNegativeButton(R.string.personal_info_photo_gallery, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                /**
                 * 刚开始，我自己也不知道ACTION_PICK是干嘛的，后来直接看Intent源码，
                 * 可以发现里面很多东西，Intent是个很强大的东西，大家一定仔细阅读下
                 */
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);

                /**
                 * 下面这句话，与其它方式写是一样的效果，如果：
                 * intent.setData(MediaStore.Images
                 * .Media.EXTERNAL_CONTENT_URI);
                 * intent.setType(""image/*");设置数据类型
                 * 如果朋友们要限制上传到服务器的图片类型时可以直接写如
                 * ："image/jpeg 、 image/png等的类型"
                 * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
                 */
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 1);

            }
        }).setPositiveButton(R.string.personal_info_photograph, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
                /**
                 * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
                 * 文档，you_sdk_path/docs/guide/topics/media/camera.html
                 * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
                 * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
                 */
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/LaikanReader", "person.jpg")));

                startActivityForResult(intent, 2);
            }
        }).show();
    }

    /**
     * 选择提示对话框
     */
    private void upImage(final Bitmap photo) {
        new AlertDialog.Builder(mContext).setTitle(R.string.personal_info_whether_upload).setNegativeButton(R.string.personal_info_yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // bitmapToFile(photo, photo.getWidth(),
                // photo.getHeight());
                Drawable drawable = new BitmapDrawable(photo);
                icon.setImageDrawable(drawable);
                bitmapToFile(photo, 300, 300);

            }
        }).setPositiveButton(R.string.personal_info_no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
                // Drawable drawable = new BitmapDrawable(photo);
                // icon.setImageDrawable(drawable);
            }
        }).show();
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
		 * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
		 */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            final Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            icon.setImageDrawable(drawable);
            upImage(photo);
        }
    }

    public void bitmapToFile(Bitmap bmp, int width, int height) {

        FileOutputStream fop;
        try {
            fop = new FileOutputStream(Environment.getExternalStorageDirectory() + "/LaikanReader/person.jpg");
            // 实例化FileOutputStream，参数是生成路径
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fop);
            // 压缩bitmap写进outputStream 参数：输出格式 输出质量 目标OutputStream
            // 格式可以为jpg,png,jpg不能存储透明
            fop.close();
            // 关闭流
            try {
                uploadimg(new File(Environment.getExternalStorageDirectory() + "/LaikanReader/person.jpg"), width, height);
            }catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @param json 要保存的json字符串
     * @param filePath 存放的文件路径
     */
    private void saveFile(String json, String filePath) {

        File file = PublicUtil.getRootPath();
        file = new File(file.getPath() + filePath);
        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        file_url = file.getPath();
        FileUtil.writeFile(file.getPath(), json);
    }

    /**
     * 读取json文件
     */
    private void readFile() {
        try {
            File file = PublicUtil.getRootPath();
            String json = FileUtil.readFileString(file.getPath() + PERSONFILEPATH);
            Gson gson = new Gson();
            Type type = new TypeToken<BaseDataBean<PersonalBean<TickBean>>>() {
            }.getType();

            BaseDataBean<PersonalBean<TickBean>> result;
            result = gson.fromJson(json, type);
            mData = result.getData();
            if (result.getData().getUsercenterMenu() == null) {
                layout_item4_3.setVisibility(View.GONE);
            }else {
                setActivity(result.getData().getUsercenterMenu());
            }
            setView();
        }catch (NullPointerException e) {
            e.printStackTrace();
            if (ActivityUitl.isNetworkAvailable(mContext)) {
                if (BookFileUtils.isNoLogin()) {
                    ToastMgr.showShortToast(R.string.personal_no_login);
                    no_login();
                }else {
                    getData();
                }
            }else {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }
        }
    }

    /**
     * 上传文件到服务器
     *
     * @param file 需要上传的文件
     * @param RequestURL 请求的rul
     *
     * @return 返回响应的内容
     */
    public int uploadFile(File file, String RequestURL, Bitmap photo) {
        int res = 0;
        String url_p = RequestURL;
        url_p = RequestURL + "?sd=" + SPUtil.getString("token", "") + "&left=0&top=0&width=100&height=100";
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型

        try {
            URL url = new URL(url_p);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("Content-type", "text/html");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

            if (file != null) {
                /**
                 * 当文件不为空时执行上传
                 */
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名
                 */

                sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                // InputStream is = new FileInputStream(file);
                InputStream is = Bitmap2IS(photo);

                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流
                 */
                res = conn.getResponseCode();
                KLog.e(TAG, "response code:" + res);
                if (res == 200) {
                    KLog.e(TAG, "request success");
                    InputStream input = conn.getInputStream();
                    InputStreamReader isr = new InputStreamReader(input, "UTF-8");
                    BufferedReader bufr = new BufferedReader(isr);
                    String line = null;
                    while ((line = bufr.readLine()) != null) {
                        KLog.e("", "line = " + line);
                    }

                    StringBuffer sb1 = new StringBuffer();
                    int ss;
                    while ((ss = input.read()) != -1) {
                        sb1.append((char)ss);
                    }
                    result = sb1.toString();
                    KLog.e(TAG, "result : " + result);
                }else {
                    KLog.e(TAG, "request error");
                }
            }
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public String getPath(Uri uri) {
        if (uri == null) {
            return null;
        }
        String path;
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            path = cursor.getString(column_index);
            cursor.close();
        }else {
            path = uri.getPath();
        }
        return path;
    }

    private InputStream Bitmap2IS(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        InputStream sbs = new ByteArrayInputStream(baos.toByteArray());
        return sbs;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 2秒内连续按两次 退出程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mkeyTime) > 2000) {
                mkeyTime = System.currentTimeMillis();
                Toast.makeText(this, R.string.personal_exit_program, Toast.LENGTH_SHORT).show();
            }else {
                finish();
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
